#include<iostream>
#include<unordered_map>
#include<string>
#include<fstream>
#include"Util.hpp"
#include"compiler.hpp"
#include"cpp-httplib-master/httplib.h"
#include<jsoncpp/json/json.h>

int main() {
   
    httplib::Server svr;/*创建server服务器对象*/
    LOG(INFO, "hello world");
    std::string output; 
    FileUtil::ReadFile("./log.txt", output);
    std::cout << output << std::endl;
    /*返回提交代码的页面*/
    svr.Get("/compile", [&](const httplib::Request& req, httplib::Response& res){
        (void) req; 
        std::ifstream ifs("./web/compile.html"); 
        if (!ifs.is_open()) {
            LOG(ERROR, "open file error");
            return;
        }
        std::string response;
        while (!ifs.eof()) {
          std::string tmp;
          getline(ifs, tmp);
          response += tmp; 
        }
        ifs.close();
        res.set_content(response, "text/html");
    });
    /*返回提交代码结果的页面*/
    svr.Post("/compile/1", [&](const httplib::Request& req, httplib::Response& res){
        LOG(INFO, req.body);
        /*将输入转成Json格式*/
        std::unordered_map<std::string, std::string> kv_map;/*将req进行切分*/
        UrlUtil::UrlParse(req.body, kv_map); 
        /*code和input*/
        Json::Value js_req;
        for (auto& i: kv_map) {
            js_req[i.first] = i.second; 
            LOG(INFO, i.first + ":" + i.second);
        } 
        /*进行编译,构建json格式响应*/
        Json::Value js_res;
        Compile::CompileAndRun(js_req, js_res); 
        std::string html;
        for (auto& i :js_res) {
            html += i.asString(); 
        }
        /*这里string中有'\n',但是浏览器上没有,因为html的换行不是\n,可以到时候在html页面中使用<pre>标签*/
        res.set_content(html, "text/html");
    });
    svr.set_base_dir("./Web", "/");
    svr.listen("0.0.0.0", 8080);
    return 0;
}
